#!/usr/bin/env bash

source ./config/env.sh
clear

mkdir -p ${K8S_DATA}/config/metrics-server/yaml

mkdir -p ${K8S_CA_DIR}/metrics-server

cat > ${K8S_CA_DIR}/metrics-server/metrics-server-csr.json <<EOF
{
  "CN": "aggregator",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF

cd ${K8S_CA_DIR}/metrics-server

cfssl gencert -ca=${K8S_CA_DIR}/admin/ca.pem \
  -ca-key=${K8S_CA_DIR}/admin/ca-key.pem  \
  -config=${K8S_CA_DIR}/admin/ca-config.json  \
  -profile=kubernetes metrics-server-csr.json | cfssljson -bare metrics-server

for master_ip in ${MASTER_IP}
do
    echo "=========================================== ${master_ip} ==========================================="
    ssh root@${master_ip} "test -e ${K8S_CA_DIR}/metrics-server || mkdir -p ${K8S_CA_DIR}/metrics-server"
    scp metrics-server*.pem root@${master_ip}:${K8S_CA_DIR}/metrics-server
done


for node_ip in ${NODE_IP}
do
    echo "=========================================== ${node_ip} ==========================================="
    ssh root@${node_ip} "test -e ${K8S_CA_DIR}/metrics-server || mkdir -p ${K8S_CA_DIR}/metrics-server"
    scp metrics-server*.pem root@${node_ip}:${K8S_CA_DIR}/metrics-server
done

# for master_ip in ${MASTER_IP}
# do
#   echo "=========================================== ${master_ip} ==========================================="
#   ssh root@${master_ip} "sed '50 i \ \ \--enable-aggregator-routing=true' -i /etc/systemd/system/kube-apiserver.service"
#   ssh root@${master_ip} "systemctl daemon-reload && systemctl restart kube-apiserver"
# done



cp ${K8S_DATA}/unpack/kubernetes/cluster/addons/metrics-server/* ${K8S_DATA}/config/metrics-server/yaml
cp ${K8S_DATA}/config/metrics-server/yaml/metrics-server-deployment.yaml{,.orig}


sed -i "s#k8s.gcr.io/metrics-server-amd64:v0.3.1#mirrorgooglecontainers/metrics-server-amd64:v0.3.1#g" ${K8S_DATA}/config/metrics-server/yaml/metrics-server-deployment.yaml
sed -i "s#k8s.gcr.io/addon-resizer:1.8.4#siriuszg/addon-resizer:1.8.4#g" ${K8S_DATA}/config/metrics-server/yaml/metrics-server-deployment.yaml

cat > ${K8S_DATA}/config/metrics-server/yaml/auth-kubelet.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: metrics-server:system:kubelet-api-admin
  labels:
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: Reconcile
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:kubelet-api-admin
subjects:
- kind: ServiceAccount
  name: metrics-server
  namespace: kube-system
EOF

cd ${K8S_DATA}/config/metrics-server/yaml/

${K8S_BIN_DIR}/kubectl create -f .